package com.huaruan.youdi.utils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;

public class GsonUtil {

    public static Object parseResponse(String result, final Class<?> tClass){

        try {
            Gson mGson = new Gson();
            JsonParser parser = new JsonParser();
            JsonObject jsonObject = parser.parse(result).getAsJsonObject();
            final JsonElement element = jsonObject.get("data");

            if(tClass ==null){
                return element.toString().replace("\"", "");
            }else if (element.isJsonObject()) {
                final Object objectResult = mGson.fromJson(element, tClass);
                return objectResult;
            } else if (element.isJsonArray()) {
                JsonArray jsonArray = element.getAsJsonArray();
                final List<Object> list = new ArrayList<>();
                int length = jsonArray.size();
                for (int i = 0; i < length; i++) {
                    JsonElement jsonElement = jsonArray.get(i);
                    if (jsonElement.isJsonObject()) {
                        list.add(mGson.fromJson(jsonElement.getAsJsonObject(), tClass));
                    } else {
                        list.add(jsonElement.getAsString());
                    }
                }
                return list;
            }
        } catch (Exception e) {
                return null;
        }
        return null;
    }
}
